package com.coment.game.core;

import com.coment.cfg.luban.roles.NumericalConfig;
import com.coment.game.fight.Attrs;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import lombok.Getter;

import java.util.HashMap;
import java.util.Map;

/// 属性字段映射器
@Getter
public final class AttributeFieldMapper {
    private static final Gson gson = new Gson();
    private final Map<String, Integer> fieldNameToIdMap;


    public AttributeFieldMapper(HashMap<Integer, NumericalConfig> dataMap) {
        fieldNameToIdMap = new HashMap<>();
        for (Map.Entry<Integer, NumericalConfig> entry : dataMap.entrySet()) {
            NumericalConfig numericalConfig = entry.getValue();
            fieldNameToIdMap.put(numericalConfig.ConstName, numericalConfig.NumericalID);
        }
    }

    public Attrs obtainAttrs(Object obj) {
        // 对象转json
        JsonObject jsonObject = gson.toJsonTree(obj).getAsJsonObject();

        Attrs result = new Attrs();

        // 遍历JSON对象的所有属性
        for (Map.Entry<String, JsonElement> entry : jsonObject.entrySet()) {
            String fieldName = entry.getKey();

            JsonElement value = entry.getValue();

            // 查找字段名对应的ID
            Integer fieldId = fieldNameToIdMap.get(fieldName);
            if (fieldId != null && value.isJsonPrimitive()) {
                try {
                    // 尝试将值转换为Double
                    Double fieldValue = value.getAsDouble();
                    result.put(fieldId, fieldValue);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }
}

